package com.example.blog_springboot.controller;

import com.example.blog_springboot.api.BlogRest;
import com.example.blog_springboot.api.config.exception.NullException;
import com.example.blog_springboot.model.Blog;
import com.example.blog_springboot.model.User;
import com.example.blog_springboot.service.BlogService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
public class BlogController implements BlogRest {

    @Autowired
    private BlogService blogService;

    @Override
    public List<Blog> selectAll(){
        return blogService.selectAll();
    }

    @Override
    public Blog selectOne(String blogId) throws Exception {
        if (StringUtils.isBlank(blogId)){
            throw new Exception();
        }
        return blogService.selectOne(blogId);
    }

    @Override
    public void add(Blog blog,@SessionAttribute("user")User user) throws Exception {
        if (StringUtils.isBlank(blog.getTitle()) || StringUtils.isBlank(blog.getContent())){
            throw new NullException();
        }
        blogService.add(blog,user);
    }

    @Override
    public void delete(String blogId, @SessionAttribute("user")User user) throws Exception {
        if (StringUtils.isBlank(blogId)){
            throw new Exception();
        }
        blogService.delete(blogId,user);
    }

    @Override
    public int count(){
        List<Blog> list = blogService.selectAll();
        return list.size();
    }
}